from datetime import timedelta
from django.utils import timezone

from django.db.models import Q
from django.http import HttpResponse, JsonResponse, FileResponse, Http404
from django.views.decorators.http import require_GET, require_POST

from app01.models import User, Stamp, UserStamp, Letter
from utils.auth import c2s, already_authorized
from xinfou1 import settings
from django.views import View, generic
import json
import utils.response
from utils.response import wrap_json_response, CommonResponseMixin, ReturnCode
from utils import utils

# 获取近期邮件（5条）
from xinfou1.settings import MEDIA_ROOT


@require_GET
def get_recent(request):
    require = ['user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('user_id'))
        if user.count == 0:
            return JsonResponse(utils.user_missing())

        user = user[0]
        now = timezone.now()
        mails = list(
            Letter.objects.filter(receive_user=user, receive_time__lt=now).order_by('-receive_time')[:5].values(
                'letter_id', 'stamp__id', 'receive_time', 'post_user__nickname', 'post_user__province',
                'post_user__city', 'text'))
        datas = []
        for mail in mails:
            receive_time = mail.get('receive_time').strftime('%Y-%m-%d-%H-%M').split('-')
            date = [int(receive_time[0]), int(receive_time[1]), int(receive_time[2]), int(receive_time[3]),int(receive_time[4])]
            data = {
                "mail_id": mail.get('letter_id'),
                "stamp_id": mail.get('stamp__id'),
                "receive_time": date,
                "post_name": mail.get('post_user__nickname'),
                "province": mail.get('post_user__province'),
                "city": mail.get('post_user__city'),
                "text" : mail.get('text')
            }
            datas.append(data)

        return JsonResponse(utils.get_response(0, '获取近期邮件', datas))
    else:
        return JsonResponse(utils.parameters_missing())


# 获取与某个笔友的所有邮件列表 (包含用户发给笔友和笔友发给用户的，按照时间降序排列)
@require_GET
def get_all_mail(request):
    require = ['user_id', 'pal_user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('user_id'))
        pal = User.objects.filter(user_id=request.GET.get('pal_user_id'))
        if user.count == 0 or pal.count == 0:
            return JsonResponse(utils.user_missing())
        user = user[0]
        pal = pal[0]
        now = timezone.now()
        mails = list(Letter.objects. \
                     filter(
            Q(post_user=user, receive_user=pal, receive_time__lt=now) | Q(post_user=pal, receive_user=user,
                                                                          receive_time__lt=now)). \
                     order_by('-receive_time'). \
                     values('letter_id', 'stamp__id', 'receive_time', 'post_user__nickname', 'text'))
        datas = []
        print(len(mails))
        for mail in mails:
            receive_time = mail.get('receive_time').strftime('%Y-%m-%d-%H-%M').split('-')
            date = [int(receive_time[0]), int(receive_time[1]), int(receive_time[2]), int(receive_time[3]),int(receive_time[4])]
            data = {
                "mail_id": mail.get('letter_id'),
                "stamp_id": mail.get('stamp__id'),
                "receive_time": date,
                "post_name": mail.get('post_user__nickname'),
                "text": mail.get('text')
            }
            datas.append(data)

        return JsonResponse(utils.get_response(0, '获取与某个笔友的所有邮件列表', datas))
    else:
        return JsonResponse(utils.parameters_missing())


# 获取邮票icon
@require_GET
def get_icon(request):
    require = ['stamp_id']
    if utils.parameters_judge(require, request.GET.keys()):
        stamp = Stamp.objects.get(id=request.GET.get('stamp_id'))
        datas = [stamp.url]
        return JsonResponse(utils.get_response(0, '获取邮票icon', datas))
    else:
        return JsonResponse(utils.parameters_missing())


# 获取所有邮票的id和name
@require_GET
def get_stamp_idAndName(request):
    require = ['stamp_id']
    if utils.parameters_judge(require, request.GET.keys()):
        stamp = Stamp.objects.get(id=request.GET.get('stamp_id'))
        datas = [stamp.url]
        return JsonResponse(utils.get_response(0, '获取邮票icon', datas))
    else:
        return JsonResponse(utils.parameters_missing())


# 获取某一信件的详细内容
@require_GET
def get_mail_detail(request):
    require = ['mail_id']
    if utils.parameters_judge(require, request.GET.keys()):
        mail = Letter.objects.filter(letter_id=request.GET.get('mail_id')). \
            values('post_user__nickname', 'receive_time', 'text', 'stamp__id', 'post_user__image_url', 'post_user__province',
                   'post_user__city', 'picture', 'post_user__user_id')
        if mail.count == 0:
            return JsonResponse(utils.get_response(1, '此信不存在', None))
        mail = mail[0]
        receive_time = mail.get('receive_time').strftime('%Y-%m-%d-%H-%M').split('-')
        date = [int(receive_time[0]), int(receive_time[1]), int(receive_time[2]), int(receive_time[3]),int(receive_time[4])]
        datas = [
            {
                "post_name": mail.get('post_user__nickname'),
                "receive_time": date,
                "text": mail.get('text'),
                "stamp_id": mail.get('stamp__id'),
                "post_icon": mail.get('post_user__image_url'),
                "province": mail.get('post_user__province'),
                "city": mail.get('post_user__city'),
                "picture": mail.get('picture'),
                "post_user_id"  : mail.get('post_user__user_id')
            }
        ]
        return JsonResponse(utils.get_response(0, '获取某一信件的详细内容', datas))
    else:
        return JsonResponse(utils.parameters_missing())


# 写信 （最多携带一张图片）
@require_POST
def post_email(request):
    require = ['user_id', 'receive_user_id', 'stamp_id', 'text']
    if utils.parameters_judge(require, request.POST.keys()):
        user = User.objects.filter(user_id=request.POST.get('user_id'))
        receive_user = User.objects.filter(user_id=request.POST.get('receive_user_id'))
        if user.count() == 0 or receive_user == 0:
            return JsonResponse(utils.user_missing())
        else:
            user = user[0]
            receive_user = receive_user[0]
            sta = Stamp.objects.get(id=request.POST.get('stamp_id'))

            # 判断用户是否持有该邮票
            user_sta = UserStamp.objects.filter(user=user, stamp=sta)
            if user_sta.count() == 0:
                return JsonResponse(utils.get_response(1, '用户未持有此邮票', None))

            # 判断邮票数量是否充足
            user_sta = user_sta[0]
            if user_sta.mount == 0:
                return JsonResponse(utils.get_response(1, '此邮票数量不足', None))
            user_sta.mount -= 1
            user_sta.save()

            # 计算延迟时间
            post_location = user.city
            receive_location = receive_user.city
            delay_time = utils.get_delay_time(post_location, receive_location)

            text = request.POST.get('text')

            # TODO 保存图片 不会写 写的很烂 picture数据库里面存的是绝对地址 need to test
            picture = request.FILES.get('picture')

            url = 'http://zhouxug.cn:81/'


            letter = Letter(post_user=user, receive_user=receive_user, stamp=sta, text=text, delay_hour=delay_time,
                            picture=picture)
            letter.save()
            letter.picture = url + str(letter.picture)
            # 计算收到时间
            letter.receive_time = letter.post_time + timedelta(hours=delay_time)
            letter.save()

            # 修改发件数和收件数
            user.post += 1
            receive_user.receive += 1
            user.save()
            receive_user.save()

            return JsonResponse(utils.get_response(0, '写信', None))
    else:
        return JsonResponse(utils.parameters_missing())

@require_POST
def post_no_img(request):
    require = ['user_id', 'receive_user_id', 'stamp_id', 'text']
    if utils.parameters_judge(require, request.POST.keys()):
        user = User.objects.filter(user_id=request.POST.get('user_id'))
        receive_user = User.objects.filter(user_id=request.POST.get('receive_user_id'))
        if user.count() == 0 or receive_user == 0:
            return JsonResponse(utils.user_missing())
        else:
            user = user[0]
            receive_user = receive_user[0]
            sta = Stamp.objects.get(id=request.POST.get('stamp_id'))

            # 判断用户是否持有该邮票
            user_sta = UserStamp.objects.filter(user=user, stamp=sta)
            if user_sta.count() == 0:
                return JsonResponse(utils.get_response(1, '用户未持有此邮票', None))

            # 判断邮票数量是否充足
            user_sta = user_sta[0]
            if user_sta.mount == 0:
                return JsonResponse(utils.get_response(1, '此邮票数量不足', None))
            user_sta.mount -= 1
            user_sta.save()

            # 计算延迟时间
            post_location = user.city
            receive_location = receive_user.city
            delay_time = utils.get_delay_time(post_location, receive_location)

            text = request.POST.get('text')

            letter = Letter(post_user=user, receive_user=receive_user, stamp=sta, text=text, delay_hour=delay_time)
            letter.save()

            # 计算收到时间
            letter.receive_time = letter.post_time + timedelta(hours=delay_time)
            letter.save()

            # 修改发件数和收件数
            user.post += 1
            receive_user.receive += 1
            user.save()
            receive_user.save()

            return JsonResponse(utils.get_response(0, '写信', None))
    else:
        return JsonResponse(utils.parameters_missing())


# 获取是否有正在路上的信件
@require_GET
def get_is_emailing(request):
    require = ['user_id']
    if utils.parameters_judge(require, request.GET.keys()):
        user = User.objects.filter(user_id=request.GET.get('user_id'))
        if user.count == 0:
            return JsonResponse(utils.user_missing())
        user = user[0]

        now = timezone.now()
        print(now)
        mails = Letter.objects.filter(receive_user=user, receive_time__gte=now).count()
        datas = [mails]
        return JsonResponse(utils.get_response(0, '在路上信件的数量', datas))
    else:
        return JsonResponse(utils.parameters_missing())
